﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;
using LightInject;
using Mnk.Library.WpfControls.Components.CheckableTreeView;

namespace HappyBa.Pages
{
    /// <summary>
    /// Interaction logic for TasksInProgressPage.xaml
    /// </summary>
    public partial class TasksInProgressPage 
    {
        private IDataCache dataCache;
        private Config config;
        private readonly ObservableCollection<Node> nodes = new ObservableCollection<Node>();
        private readonly IServiceContainer container;

        public TasksInProgressPage()
        {
            InitializeComponent();
            container = ((MainWindow)Application.Current.MainWindow).Container;
            container.GetInstance<IDataCollector>().OnDataChanged += (o, e) => OnDataContextChanged(o, new DependencyPropertyChangedEventArgs());
            DataContextChanged += OnDataContextChanged;
            Items.ItemsSource = nodes;
        } 

        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
        {
            dataCache = container.GetInstance<IDataCache>();
            config = container.GetInstance<Config>();
            if (config.Current == null) return;

            var metrics = new Metrics(dataCache.Metrics.Data, new MetricsSearch(config.Current.Search));
            var users = metrics.Users.Where(metrics.IsDeveloper).ToArray();
            var items = metrics
                .Bugs.Cast<UIEstimatableEntityBase>()
                .Concat(metrics.Tasks)
                .Where(metrics.IsInProgress)
                .ToArray();
            Info.Text = string.Format("Tasks: {0}, Bugs: {1}", 
                items.Count(metrics.IsTask),
                items.Count(metrics.IsBug)
                );
            var work = users
                .Where(i => config.Current.ActiveEmployees.Select(e => e.Key).Contains(i.ToString()))
                .Select(
                x=>new UserTasks
                {
                    Entity = x,
                    Items = items
                        .Where(i=>i.Assignments.Any(a=>a.GeneralUser.Id==x.Id))
                        .Cast<UIStatebleEntityBase>()
                        .ToArray()
                }).ToArray();
            SetItems(work);
        }

        private void SetItems(IEnumerable<UserTasks> items)
        {
            nodes.Clear();
            if (items != null)
            {
                foreach (var item in items)
                {
                    nodes.Add(BuildTree(item, false));
                }
            }
            Items.Items.Refresh();
        }


        private static Node BuildTree(UserTasks item, bool childrensFinded, params Node[] parents)
        {
            var node = new Node { Data = item, IsExpanded = !childrensFinded };
            foreach (var parent in parents)
            {
                node.Parent.Add(parent);
            }
            var childs = node.Data.Children;
            foreach (var ch in childs)
            {
                var child = ((NodeEntityAdapter)ch).Entity;
                node.Children.Add(BuildTree(child, childrensFinded || childs.Count > 1, node));
            }
            return node;
        }

        private static Node BuildTree(UIEntityBase item, bool childrensFinded, params Node[] parents)
        {
            var node = new Node { Data = new NodeEntityAdapter(item), IsExpanded = !childrensFinded };
            foreach (var parent in parents)
            {
                node.Parent.Add(parent);
            }
            var childs = node.Data.Children;
            foreach (var ch in childs)
            {
                var child = ((NodeEntityAdapter)ch).Entity;
                node.Children.Add(BuildTree(child, childrensFinded || childs.Count > 1, node));
            }
            return node;
        }

        private void RefreshClick(object sender, RoutedEventArgs e)
        {
            OnDataContextChanged(sender,new DependencyPropertyChangedEventArgs());
        }

        private void SelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (Items.SelectedValue != null)
            {
                var data = ((Node)Items.SelectedValue).Data as NodeEntityAdapter;
                if (data != null)
                {
                    var entity = data.Entity;
                    View.DataContext = entity;
                    return;
                }
            }
            View.DataContext = null;
        }
    }
}
